//
//  HouseDetailCell1.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/12.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "HouseDetailCell1.h"
#import "HouseTypeData.h"
#import "UIImageView+WebCache.h"
#import "StringTool.h"
#import "config.h"

#import "StringTool.h"
#import "UserModal.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "Tools.h"

#import "PhotoShowManage.h"
#import "CalculatorViewController.h"
#import "NSString+category.h"
#import "Tools.h"
#import "API.h"

#define NameFont [UIFont systemFontOfSize:13]

@interface HouseDetailCell1()<UIScrollViewDelegate,MWPhotoBrowserDelegate>

//房屋图片
@property (weak, nonatomic) IBOutlet UIImageView *houseImg;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (strong, nonatomic) UIPageControl *myPageControl;

//房屋名称
@property (weak, nonatomic) IBOutlet UILabel *houseName;
//房屋地址
@property (weak, nonatomic) IBOutlet UILabel *houseAddress;
//所属楼盘
@property (weak, nonatomic) IBOutlet UILabel *siteName;
//美金
@property (weak, nonatomic) IBOutlet UILabel *dollarLab;
//人民币
@property (weak, nonatomic) IBOutlet UILabel *renMinBiLab;
//编号
@property (weak, nonatomic) IBOutlet UILabel *serialNumLab;
//类型（别墅）
@property (weak, nonatomic) IBOutlet UILabel *houseStyleLab;
//装修（精装修）
@property (weak, nonatomic) IBOutlet UILabel *houseDecorateLab;
//状态（在售）
@property (weak, nonatomic) IBOutlet UILabel *houseStatusLab;
//邮编
@property (weak, nonatomic) IBOutlet UILabel *codeNumLab;
//房屋面积
@property (weak, nonatomic) IBOutlet UILabel *houseAreaLab;
//卧室（1间）
@property (weak, nonatomic) IBOutlet UILabel *bedroomNumLab;
//浴室（1间）
@property (weak, nonatomic) IBOutlet UILabel *bathroomNumLab;
//车库(1间）
@property (weak, nonatomic) IBOutlet UILabel *carportNumLab;
//楼层数（2层）
@property (weak, nonatomic) IBOutlet UILabel *floorNumLab;
@property (weak, nonatomic) IBOutlet UIView *teseView;
//房屋类型
@property (weak, nonatomic) IBOutlet UILabel *houseTypeLab;

//换线位置
@property (weak, nonatomic) IBOutlet UILabel *checkLineLab;

//预计租金收入
@property (weak, nonatomic) IBOutlet UILabel *rentMoneyLab;
//预计年收益率
@property (weak, nonatomic) IBOutlet UILabel *yieldLab;
@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view11;

@property (nonatomic,strong) NSLayoutConstraint* conLay;;
@property (nonatomic,strong)HouseTypeData *data;
//添加特色lab的view
@property (weak, nonatomic) IBOutlet UIView *teView;

@property (nonatomic,strong)NSLayoutConstraint *laycont;

@property (weak, nonatomic) IBOutlet UIButton *fangdaiBtn;

@end

@implementation HouseDetailCell1

-(void)awakeFromNib{
    
    [self.fangdaiBtn setAttributedTitle:[NSString makeLineStyle:@" 房贷计算器" color:UIColorFromRGB(0xdb2a2b) fontSize:12] forState:UIControlStateNormal];
}
+(instancetype) cellWithTableView:(UITableView *)tableview  data:(HouseTypeData *)data;
{
    
    HouseDetailCell1 *cell = [[[NSBundle mainBundle]loadNibNamed:@"HouseDetailCell1" owner:nil options:nil]lastObject];
    
    cell.scrollview.pagingEnabled = YES;
    cell.scrollview.showsHorizontalScrollIndicator = NO;
    cell.scrollview.showsVerticalScrollIndicator = NO;

    cell.data = data;
    
    for (NSLayoutConstraint *constran in cell.teView.constraints) {
        if (constran.firstItem == cell.teView && constran.firstAttribute == NSLayoutAttributeHeight ) {
            
            cell.laycont = constran;
        }
        break;
    }
    
         return cell;
}

-(void)layoutSubviews{
    
    [self setTeseLab:self.data];
    
    NSLog(@"1  self.teView layoutIfNeeded");
}
#pragma mark scrollView的代理
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    CGFloat offsizeX = scrollView.contentOffset.x;
    NSInteger page = offsizeX/UIScreenWidth;
    self.myPageControl.currentPage = page;
}


-(void)setData1:(HouseTypeData *)data1
{
    _data1 = data1;
    self.scrollview.contentSize =CGSizeMake( UIScreenWidth*data1.fangyuanPicsArr.count, 200);
    
    if (data1.fangyuanPicsArr.count > 0) {
        for (NSInteger i = 0; i < data1.fangyuanPicsArr.count; i ++) {
            
            UIImage *placeholderImage = [Tools getImgByColor:UIColorFromRGB(0x999999)];
            UIButton *btn = [[UIButton alloc]init];
            if ([StringTool isBlankString:[data1.fangyuanPicsArr objectAtIndex:i]]) {
                
                 [btn sd_setBackgroundImageWithURL:nil forState:UIControlStateNormal placeholderImage:placeholderImage];
                  }else{
                      
                      NSString *url =  [API imgUrlMake:[data1.fangyuanPicsArr objectAtIndex:i]];;
                    [btn sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",url]] forState:UIControlStateNormal placeholderImage:placeholderImage];
                  }
            
            btn.frame = CGRectMake(i*UIScreenWidth, 0, UIScreenWidth, 200);
            btn.tag = i;
            btn.enabled = YES;
            self.myPageControl.hidden = NO;
            [btn addTarget:self action:@selector(btnOnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.scrollview addSubview:btn];
            
        }

    }else{
        UIImage *placeholderImage = [Tools getImgByColor:[UIColor colorWithRed:(float)0xd7/(float)0xff green:(float)0xd7/(float)0xff blue:(float)0xd7/(float)0xff alpha:1]];
        
        UIButton *btn = [[UIButton alloc]init];
        [btn setBackgroundImage:placeholderImage forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, UIScreenWidth, 200);
        btn.enabled = NO;
        self.myPageControl.hidden = YES;
        [self.scrollview addSubview:btn];

    }
    
    self.myPageControl = [[UIPageControl alloc]init];
    self.myPageControl.frame = CGRectMake((UIScreenWidth - 40)/2, 170, 40, 30);
    self.myPageControl.numberOfPages = data1.fangyuanPicsArr.count;
    self.myPageControl.currentPage = 0;
    
    self.myPageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    self.myPageControl.pageIndicatorTintColor = [UIColor grayColor];
    [self.myPageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    [self.contentView addSubview:self.myPageControl];
    
    
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    HouseTypeData *model = data1;
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    
    NSString *totalAmountCNY = [formatter stringFromNumber:[NSNumber numberWithInteger:model.totalAmountCNY]];
    NSString *totalAmountUSD = [formatter stringFromNumber:[NSNumber numberWithInteger:model.totalAmountUSD]];
    
    
    
    
//    NSString *url = [NSString stringWithFormat:@"%@%@",ImgeForwardUrl,model.thumb];
    NSString *url =  [API imgUrlMake:model.thumb];;
    [self.houseImg setBackgroundColor:NoImgColor];
         [self.houseImg sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil];
    if (![StringTool isBlankString:model.housingName] && ![StringTool isBlankString:model.houseTypeName]) {
        
        self.houseName.text = [NSString stringWithFormat:@"%@(%@)",model.housingName,model.houseTypeName];
    }
    if (![StringTool isBlankString:model.countryName] && ![StringTool isBlankString:model.stateName] && ![StringTool isBlankString:model.cityName]) {
        
        self.houseAddress.text = [NSString stringWithFormat:@"地址:%@ %@ %@",model.countryName,model.stateName,model.cityName];
    }
   
    if (![StringTool isBlankString:model.housingName]) {
        
        self.siteName.text = [NSString stringWithFormat:@"所属楼盘:%@",[UserModal shareUserModel].premise];
    }
    
    if (![StringTool isBlankString:totalAmountUSD]) {
        
        self.dollarLab.text = [NSString stringWithFormat:@"$%@",totalAmountUSD];
    }
    
    if (![StringTool isBlankString:totalAmountCNY]) {
        
      self.renMinBiLab.text = [NSString stringWithFormat:@"约¥%@万",totalAmountCNY];
    }
    
    if (![StringTool isBlankString:model.businessNo]) {
        
        self.serialNumLab.text = [NSString stringWithFormat:@"编号:%@",model.businessNo];
    }
    if (![StringTool isBlankString:model.typeName]) {
        self.houseStyleLab.text = model.typeName;
    }
    if (![StringTool isBlankString:model.decorationName]) {
       self.houseDecorateLab.text = model.decorationName;
    }
    if ([model.houseTypeName isEqualToString:@"已售"]) {
        self.houseStatusLab.text = @"已售";
    }else{
        self.houseStatusLab.text = @"在售";
    }
    
    self.codeNumLab.text = [NSString stringWithFormat:@"%ld",(long)model.zip];
    
    self.houseAreaLab.text = [NSString stringWithFormat:@"%.0f平方米",model.areaMi];
    
    self.bedroomNumLab.text = [NSString stringWithFormat:@"%ld间",(long)model.bedRoom];
    self.bathroomNumLab.text = [NSString stringWithFormat:@"%ld间",(long)model.bathRoom];
    self.carportNumLab.text = [NSString stringWithFormat:@"%ld间",(long)model.garage];
    self.floorNumLab.text = [NSString stringWithFormat:@"%ld层",(long)model.floor];
    
    self.rentMoneyLab.text = [NSString stringWithFormat:@"$%.0f/月",model.expectRent];
    self.yieldLab.text = [NSString stringWithFormat:@"%.2f%%",model.expectYield];
    

    
}

-(void)setTeseLab:(HouseTypeData *)data{
    
    if (data.houseTagsArr.count > 0) {
        
        CGSize nameMaxSize = CGSizeMake(MAXFLOAT,21);
        NSDictionary *attrs =@{NSFontAttributeName:NameFont};
        CGFloat margin = 5;
        CGFloat wsum = 0,wsum2 = 0;
        CGFloat labH = 21;
        NSInteger falg = 0;
        
        for (NSInteger i = 0; i < data.houseTagsArr.count;  i ++) {
            
            UILabel *lab = [[UILabel alloc]init];
            lab.text = [data.houseTagsArr objectAtIndex:i];
            margin = i == 0?10:5;
            CGFloat labW = [lab.text  boundingRectWithSize:nameMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width+10;
            
            if ((wsum + margin+ labW) > UIScreenWidth) {
                falg ++;
            }
            if (falg == 1) {
                margin = 10;
            }else if (falg > 1)
            {
                margin = 5;
            }
            wsum = (wsum + margin+ labW) <= UIScreenWidth ? (wsum + margin+ labW):0 + margin + labW;
            wsum2 = wsum2 + labW;
            
            CGFloat labY ;
            if (wsum2 <= UIScreenWidth) {
                labY = 5;
            }else{
                labY = 21 + 15;
                
            }
            lab.frame = CGRectMake(wsum - labW, labY, labW,labH);
            lab.frame = CGRectMake(wsum - labW, labY, labW,labH);
            lab.textColor = [UIColor whiteColor];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.font = [UIFont systemFontOfSize:13];
            lab.backgroundColor =  [[self colorArr]objectAtIndex:i];
            [self.teView addSubview:lab];
            
            NSLog(@"lab %@",NSStringFromCGRect(self.teseView.frame));
            
            
        }
        self.laycont.constant = (wsum2 <= UIScreenWidth)?40:(40+ 30);
        [self.teView layoutIfNeeded];
        
    }else{
        self.laycont.constant = 10;
        [self.teView layoutIfNeeded];
    }
    

    
}
+(CGFloat)getHeighWithTableView:(UITableView *)tableview  data:(HouseTypeData *)data;
{
    HouseDetailCell1 *cell = [HouseDetailCell1 cellWithTableView:tableview data:data];
    [cell setTeseLab:data];
    NSLog(@"2  self.teView layoutIfNeeded");
    return 610 +([cell addTesLab:data] - 40) ;
//    return [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height +1;
}

-(CGFloat)addTesLab:(HouseTypeData *)data
{
//    if (data.houseTagsArr.count > 0) {
//        
//        CGSize nameMaxSize = CGSizeMake(MAXFLOAT,21);
//        NSDictionary *attrs =@{NSFontAttributeName:NameFont};
//        CGFloat margin = 5;
//        CGFloat wsum = 0,wsum2 = 0;
//        CGFloat labH = 21;
//        
//        for (NSInteger i = 0; i < data.houseTagsArr.count;  i ++) {
//            
//            UILabel *lab = [[UILabel alloc]init];
//            lab.text = [data.houseTagsArr objectAtIndex:i];
//            margin = i == 0?10:5;
//            CGFloat labW = [lab.text  boundingRectWithSize:nameMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width+10;
//            
//            wsum = (wsum + margin+ labW) <= UIScreenWidth ? (wsum + margin+ labW):0;
//            CGFloat labY = wsum == 0 ?21:5;
//            lab.frame = CGRectMake(wsum - labW, labY, labW,labH);
//            lab.textColor = [UIColor whiteColor];
//            lab.textAlignment = NSTextAlignmentCenter;
//            lab.font = [UIFont systemFontOfSize:13];
//            lab.backgroundColor =  [[self colorArr]objectAtIndex:i];
//            [self.teView addSubview:lab];
//            wsum2 = labY + labW;
//            
//        }
//        
//        return (wsum2 <= UIScreenWidth)?40:(40+ 21);
////        self.laycont.constant = (wsum2 <= UIScreenWidth)?40:(40+ 21);
////        [self.teView layoutIfNeeded];
//        
//    }else{
//        self.laycont.constant = 30;
//        [self.teView layoutIfNeeded];
//        return 10;
//    }
    
    
    
    if (data.houseTagsArr.count > 0) {
        
        CGSize nameMaxSize = CGSizeMake(MAXFLOAT,21);
        NSDictionary *attrs =@{NSFontAttributeName:NameFont};
        CGFloat margin = 5;
        CGFloat wsum = 0,wsum2 = 0;
        CGFloat labH = 21;
        NSInteger falg = 0;
        
        for (NSInteger i = 0; i < data.houseTagsArr.count;  i ++) {
            
            UILabel *lab = [[UILabel alloc]init];
            lab.text = [data.houseTagsArr objectAtIndex:i];
            margin = i == 0?10:5;
            CGFloat labW = [lab.text  boundingRectWithSize:nameMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width+10;
            
            if ((wsum + margin+ labW) > UIScreenWidth) {
                falg ++;
            }
            if (falg == 1) {
                margin = 10;
            }else if (falg > 1)
            {
                margin = 5;
            }
            wsum = (wsum + margin+ labW) <= UIScreenWidth ? (wsum + margin+ labW):0 + margin + labW;
            wsum2 = wsum2 + labW;
            
            CGFloat labY ;
            if (wsum2 <= UIScreenWidth) {
                labY = 5;
            }else{
                labY = 21 + 15;
                
            }
            lab.frame = CGRectMake(wsum - labW, labY, labW,labH);
            lab.frame = CGRectMake(wsum - labW, labY, labW,labH);
            lab.textColor = [UIColor whiteColor];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.font = [UIFont systemFontOfSize:13];
            lab.backgroundColor =  [[self colorArr]objectAtIndex:i];
            [self.teView addSubview:lab];
            
            NSLog(@"lab %@",NSStringFromCGRect(self.teseView.frame));
            
            
        }
        self.laycont.constant = (wsum2 <= UIScreenWidth)?40:(40+ 30);
        [self.teView layoutIfNeeded];
        
        return (wsum2 <= UIScreenWidth)?40:(40+ 30);
        
    }else{
        self.laycont.constant = 10;
        [self.teView layoutIfNeeded];
        
        return 10;
    }
    


}
-(void)labBorder:(UILabel*)lab
{
    lab.layer.masksToBounds = YES;
    lab.layer.borderWidth = 1.0;
    
    lab.layer.borderColor = [UIColor colorWithRed:227/255.0 green:227/255.0 blue:227/255.0 alpha:1].CGColor;
}

#pragma mark 图片页面切换了
- (void)changePage:(UIPageControl *)sender {
    
    NSInteger page = sender.currentPage;
    self.scrollview.contentOffset = CGPointMake(page*UIScreenWidth, 0);
}

-(NSArray *)colorArr
{
    UIColor *red = UIColorFromRGB(0x58bf66);
    UIColor *black = UIColorFromRGB(0Xdb2a2b);
    UIColor *orange = UIColorFromRGB(0Xff7070);
    UIColor *green = UIColorFromRGB(0xE86E45);
    
    NSArray *arr = [[NSArray alloc]initWithObjects:red,black,orange,green ,nil];
    return arr;
}

-(void)btnOnClick:(UIButton*)sender{
    
    if(self.data1.fangyuanPicsArr.count>0){
        MWPhotoBrowser *br = [PhotoShowManage  getMWPhotoShowInstance:self];
        [br setCurrentPhotoIndex:sender.tag];
        [self.bufNvc pushViewController:br animated:YES];
    }
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.data1.fangyuanPicsArr.count;
}


- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    
    
    //   return  [MWPhoto photoWithURL:[NSURL URLWithString:headData.mainImgUrl]];
    
    if (index < self.data1.fangyuanPicsArr.count)
    {
        NSString *url =  [API imgUrlMake:[self.data1.fangyuanPicsArr objectAtIndex:index]];;

        return  [MWPhoto photoWithURL:[NSURL URLWithString:url]];
    }
    
    return nil;
    
}

#pragma mark 房贷计算器
- (IBAction)fangdaiBtnOnClick:(id)sender {
    
    [self.bufNvc pushViewController:[CalculatorViewController new] animated:YES];
}

@end
